import { PlusOutlined } from '@ant-design/icons';
import { Button, Divider, message, TreeSelect, Popconfirm, Select, Image } from 'antd';
import React, { useState, useRef } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import CreateForm from './components/CreateForm';
import UpdateForm from './components/UpdateForm';
import FormItem from 'antd/lib/form/FormItem';
import { transTitle, handleReturnArray } from '@/utils/utils';
import { queryRule, updateRule, addRule, removeRule } from './service';
import UploadImg from '@/components/UploadImg';
/**
 * 添加节点
 * @param fields
 */

const handleAdd = async (fields) => {
  const hide = message.loading('正在添加');

  try {
    await addRule({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};
/**
 * 更新节点
 * @param fields
 */

const handleUpdate = async (payload, actionRef) => {
  const hide = message.loading('正在配置');

  try {
    await updateRule(payload);
    hide();
    message.success('配置成功');
    actionRef.current.reload();
    return true;
  } catch (error) {
    hide();
    message.error('配置失败请重试！');
    return false;
  }
};
/**
 *  删除节点
 * @param selectedRows
 */

const handleRemove = async (payload, actionRef) => {
  const hide = message.loading('正在删除');

  try {
    await removeRule(payload);
    hide();
    message.success('删除成功，即将刷新');
    actionRef.current.reload();
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};
const TableList = () => {
  const [createModalVisible, handleModalVisible] = useState(false);
  const [editModalVisible, handleEditModalVisible] = useState(false);
  const [formValues, setFormValues] = useState({});
  const [treeValue, handleTreeValue] = useState();
  const [menuValues, setMenuValues] = useState([]);
  const [count, setCount] = useState({});
  const actionRef = useRef();
  const [row, setRow] = useState();
  const [facePicture, setFacePicture] = useState(null);
  const [selectedRowsState, setSelectedRows] = useState([]);
  // const commonImgUrl = 'data:image/png;base64,';
  const handleSetFacePicture = (payload) => {
    setFacePicture(payload);
  };
  const TreeOnChange = (value) => {
    handleTreeValue(value);
  };
  const columns = [
    // {
    //   title: '序号',
    //   dataIndex: 'id',
    //   hideInForm: true,
    // },
    {
      title: '名称',
      width: 240,
      dataIndex: 'name',
    },
    {
      title: '模块简述',
      width: 200,
      dataIndex: 'description',
    },
    {
      title: '语音内容',
      width: 200,
      dataIndex: 'text',
    },
    {
      title: '排序',
      width: 120,
      dataIndex: 'sort',
    },
    {
      title: '父级',
      dataIndex: 'parentId',
      width: 120,
      hideInTable: true,
      hideInSearch: true,
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <FormItem label={false}>
            <TreeSelect
              showSearch
              // style={{ width: '400px' }}
              value={treeValue}
              dropdownStyle={{ maxHeight: 800, overflow: 'auto' }}
              placeholder="请选择父级"
              allowClear
              treeDataSimpleMode
              treeData={menuValues}
              treeNodeFilterProp="title"
              treeNodeLabelProp="title"
              onChange={TreeOnChange}
            />
          </FormItem>
        );
      },
      // formItemProps: {
      //   rules: [
      //     {
      //       required: true,
      //       message: '父级为必填项',
      //     },
      //   ],
      // },
    },
    {
      title: '是否跳转',
      dataIndex: 'redirect',
      // initialValue: 'all',
      width: 120,
      valueEnum: {
        1: {
          text: '跳转',
          status: 'Success',
          value: 1,
        },
        2: {
          text: '不跳转',
          status: 'Processing',
          value: 2,
        },
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <FormItem label={false} name="redirect">
            <Select placeholder="请选择">
              {handleReturnArray(item.valueEnum, 3).map((item_in, index) => {
                if (item_in) {
                  return (
                    <Option key={index} value={item_in.value}>
                      {item_in.text}
                    </Option>
                  );
                }
              })}
            </Select>
          </FormItem>
        );
      },
    },
    {
      title: '类型',
      dataIndex: 'type',
      // initialValue: 'all',
      width: 160,
      valueEnum: {
        1: {
          text: '地方特色业务',
          status: 'Success',
          value: 1,
        },
        2: {
          text: '四川公安服务网',
          status: 'Processing',
          value: 2,
        },
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <FormItem label={false} name="type">
            <Select placeholder="请选择">
              {handleReturnArray(item.valueEnum, 3).map((item_in, index) => {
                if (item_in) {
                  return (
                    <Option key={index} value={item_in.value}>
                      {item_in.text}
                    </Option>
                  );
                }
              })}
            </Select>
          </FormItem>
        );
      },
    },
    {
      title: '是否部门',
      dataIndex: 'dept',
      hideInTable: true,
      width: 120,
      // initialValue: 'all',
      valueEnum: {
        0: {
          text: '部门',
          status: 'Success',
          value: 0,
        },
        1: {
          text: '业务模块',
          status: 'Processing',
          value: 1,
        },
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <FormItem label={false} name="dept">
            <Select placeholder="请选择">
              {handleReturnArray(item.valueEnum, 3).map((item_in, index) => {
                if (item_in) {
                  return (
                    <Option key={index} value={item_in.value}>
                      {item_in.text}
                    </Option>
                  );
                }
              })}
            </Select>
          </FormItem>
        );
      },
    },
    {
      title: 'Icon',
      dataIndex: 'icon',
      width: 40,
      hideInSearch: true,
      render: (_, payload) => {
        return (
          <>
            {' '}
            <Image
              style={{ maxHeight: '40px' , maxWidth: '40px'}}
              src={`${window.location.protocol}//${window.location.hostname}:28080/file/icon/` + _}
            />{' '}
          </>
        );
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <>
            {formValues ? (
              <FormItem name="icon">
                <UploadImg
                  imgUrl={facePicture}
                  showImgUrl={
                    `${window.location.protocol}//${window.location.hostname}:28080/file/icon/` +
                    facePicture
                  }
                  subpath="icon"
                  handleSetFacePicture={handleSetFacePicture}
                />
              </FormItem>
            ) : (
              <FormItem name="icon">
                <UploadImg subpath="icon" handleSetFacePicture={handleSetFacePicture} />
              </FormItem>
            )}
          </>
        );
      },
    },
    {
      title: '是否置灰',
      dataIndex: 'mark',
      width: 120,
      // initialValue: 'all',
      valueEnum: {
        0: {
          text: '是',
          status: 'Error',
          value: 0,
        },
        1: {
          text: '否',
          status: 'Processing',
          value: 1,
        },
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <FormItem label={false} name="mark">
            <Select placeholder="请选择">
              {handleReturnArray(item.valueEnum, 3).map((item_in, index) => {
                if (item_in) {
                  return (
                    <Option key={index} value={item_in.value}>
                      {item_in.text}
                    </Option>
                  );
                }
              })}
            </Select>
          </FormItem>
        );
      },
    },
    {
      title: '路由',
      width: 180,
      dataIndex: 'path',
    },
    {
      title: '操作',
      width: 140,
      key: 'option',
      fixed: 'right',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a
            onClick={() => {
              handleEditModalVisible(true);
              handleSetFacePicture(record.icon);
              setFormValues(record);
            }}
          >
            修改
          </a>
          <Divider type="vertical" />
          <Popconfirm
            placement="top"
            title="确定要删除吗?"
            onConfirm={() => {
              handleRemove(record.id, actionRef);
            }}
            okText="Yes"
            cancelText="No"
          >
            <a onClick={() => {}}>删除</a>
          </Popconfirm>
        </>
      ),
    },
  ];
  return (
    <PageContainer>
      <ProTable
        headerTitle="业务模块管理"
        actionRef={actionRef}
        rowKey="id"
        bordered
        options={false}
        search={false}
        toolBarRender={() => [
          <Button
            type="primary"
            onClick={() => {
              setFacePicture(null);
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={(params, sorter, filter) => queryRule({ ...params, sorter, filter })}
        postData={(params) => {
          const payload = params;
          transTitle(payload);
          setMenuValues(payload);

          return params;
        }}
        pagination={false}
        columns={columns}
        rowSelection={false}
      />
      <CreateForm
        title="添加模块"
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
      >
        <ProTable
          onSubmit={async (value) => {
            if (facePicture) {
              value.icon = facePicture;
            }
            const success = await handleAdd(value);

            if (success) {
              handleModalVisible(false);

              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          rowKey="id"
          bordered
          type="form"
          columns={columns}
        />
      </CreateForm>
      <CreateForm
        title="修改模块"
        onCancel={() => handleEditModalVisible(false)}
        modalVisible={editModalVisible}
      >
        <ProTable
          onSubmit={async (value) => {
            if (!value.hasOwnProperty('parentId')) {
              value.parentId = null;
            }
            value.icon = facePicture;
            value.id = formValues.id;
            value.version = formValues.version + 1;
            const success = await handleUpdate(value, actionRef);

            if (success) {
              handleEditModalVisible(false);

              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          form={{ initialValues: formValues }}
          rowKey="id"
          bordered
          type="form"
          columns={columns}
        />
      </CreateForm>
    </PageContainer>
  );
};

export default TableList;
